<?php

/**
 * 订单管理
 *
 * @author birdy <freebirdy@foxmail.com>
 * @link http://www.aiyuangong.com
 */

namespace app\member\controller;

class Order extends \app\common\controller\Member
{

    /**
     * 订单列表
     */
    public function index()
    {
        //搜索
        $condition = [];
        $condition['buyer_id'] = $this->member_id;
        if (input('order_sn')) {
            $condition['order_sn'] = input('order_sn');
        }
        
        $query_date = $this->query_date();
        if ($query_date && is_array($query_date)) {
            $condition['add_time'] = $query_date;
        }
        
        $state_type = input('state_type');
        if ($state_type) {
            $condition['order_state'] = str_replace(
                    array('state_new', 'state_submit', 'state_pay', 'state_send', 'state_success', 'state_noeval', 'state_cancel'), array(ORDER_STATE_NEW, ORDER_STATE_SUBMIT, ORDER_STATE_PAY, ORDER_STATE_SEND, ORDER_STATE_SUCCESS, ORDER_STATE_SUCCESS, ORDER_STATE_CANCEL), $state_type
            );
        }
        if ($state_type == 'state_noeval') {
            $condition['evaluation_state'] = 0;
            $condition['order_state'] = ORDER_STATE_SUCCESS;
        }

        //回收站
        $recycle = input('recycle/d') > 0 ? 1 : 0;
        if ($recycle) {
            $condition['delete_state'] = 1;
        } else {
            $condition['delete_state'] = 0;
        }

        $model_order = model('Common/Order');
        
        $pageConfig = [
            'path' => url('member/order/index'),
            'query' => $this->request->param(),
            'page' => input('curpage/d') ? : 1,
            'type' => '\\Page',
            'var_page' => 'curpage'
        ];
        
        $order_list = $model_order->getOrderList($condition, 20, '*', 'order_id desc', $pageConfig, array('order_common', 'order_goods', 'store'));
        if (isset($order_list['page'])) {
            $this->assign('show_page', $order_list['page']);
        }
        $order_list = $order_list['list'] ? : [];

        $model_refund_return = model('Common/RefundReturn');
        $order_list = $model_refund_return->getGoodsRefundList($order_list);

        //订单列表以支付单pay_sn分组显示
        $order_group_list = [];
        $order_pay_sn_array = [];
        $order_pay_list = [];
        if ($order_list) {
            foreach ($order_list as $order_id => $order) {

                //显示取消订单
                $order['if_cancel'] = $model_order->getOrderOperateState('buyer_cancel', $order);

                //显示退款取消订单
                $order['if_refund_cancel'] = $model_order->getOrderOperateState('refund_cancel', $order);

                //显示投诉
                $order['if_complain'] = $model_order->getOrderOperateState('complain', $order);

                //显示收货
                $order['if_receive'] = $model_order->getOrderOperateState('receive', $order);

                //显示锁定中
                $order['if_lock'] = $model_order->getOrderOperateState('lock', $order);

                //显示物流跟踪
                $order['if_deliver'] = $model_order->getOrderOperateState('deliver', $order);

                //显示评价
                $order['if_evaluation'] = $model_order->getOrderOperateState('evaluation', $order);

                //显示删除订单(放入回收站)
                $order['if_delete'] = $model_order->getOrderOperateState('delete', $order);

                //显示永久删除
                $order['if_drop'] = $model_order->getOrderOperateState('drop', $order);

                //显示还原订单
                $order['if_restore'] = $model_order->getOrderOperateState('restore', $order);

                foreach ($order['extend_order_goods'] as $value) {
                    $value['image_60_url'] = img_url($value['goods_image'], 60);
                    $value['image_240_url'] = img_url($value['goods_image'], 240);
                    $value['goods_type_cn'] = orderGoodsType($value['goods_type']);
                    $value['goods_url'] = url('index/goods/detail', array('goods_id' => $value['goods_id']));
                    if ($value['goods_type'] == 5) {
                        $order['zengpin_list'][] = $value;
                    } else {
                        $order['goods_list'][] = $value;
                    }
                }

                if (empty($order['zengpin_list'])) {
                    $order['goods_count'] = count($order['goods_list']);
                } else {
                    $order['goods_count'] = count($order['goods_list']) + 1;
                }
                $order_group_list[$order['pay_sn']]['order_list'][] = $order;

                //如果有在线支付且未付款的订单则显示合并付款链接
                if ($order['order_state'] == ORDER_STATE_NEW) {
                    $order_group_list[$order['pay_sn']]['pay_amount'] += $order['order_amount'] - $order['pd_amount'] - $order['rcb_amount'];
                }
                $order_group_list[$order['pay_sn']]['add_time'] = $order['add_time'];

                //记录一下pay_sn，后面需要查询支付单表
                $order_pay_sn_array[] = $order['pay_sn'];
            }

            //取得这些订单下的支付单列表
            $condition = array('pay_sn' => array('in', array_unique($order_pay_sn_array)));
            $order_pay_list = reset_by_key($model_order->getOrderPayList($condition, '', '*', ''), 'pay_sn');
            foreach ($order_group_list as $pay_sn => $pay_info) {
                $order_group_list[$pay_sn]['pay_info'] = $order_pay_list[$pay_sn];
            }
        }

        $this->assign('order_group_list', $order_group_list);
        $this->assign('order_pay_list', $order_pay_list);

        $this->profile_menu(input('recycle') ? 'member_order_recycle' : 'member_order');
        return view();
    }

    //订单详情
    public function detail()
    {
        $order_id = input('order_id/d');
        if ($order_id <= 0) {
            return $this->error('该订单不存在');
        }
        $model_order = model('Common/Order');
        $condition = array();
        $condition['order_id'] = $order_id;
        $condition['buyer_id'] = $this->member_id;
        $order_info = $model_order->getOrderInfo($condition, array('order_goods', 'order_common', 'store'));
        if (empty($order_info) || $order_info['delete_state'] == ORDER_DEL_STATE_DROP) {
            return $this->error('该订单不存在');
        }

        $model_refund_return = model('Common/RefundReturn');
        $order_list = array();
        $order_list[$order_id] = $order_info;
        $order_list = $model_refund_return->getGoodsRefundList($order_list, 1); //订单商品的退款退货显示
        $order_info = $order_list[$order_id];
        $refund_all = $order_info['refund_list'][0];
        if (!empty($refund_all) && $refund_all['seller_state'] < 3) {//订单全部退款商家审核状态:1为待审核,2为同意,3为不同意
            $this->assign('refund_all', $refund_all);
        }

        //显示锁定中
        $order_info['if_lock'] = $model_order->getOrderOperateState('lock', $order_info);

        //显示取消订单
        $order_info['if_cancel'] = $model_order->getOrderOperateState('buyer_cancel', $order_info);

        //显示退款取消订单
        $order_info['if_refund_cancel'] = $model_order->getOrderOperateState('refund_cancel', $order_info);

        //显示投诉
        $order_info['if_complain'] = $model_order->getOrderOperateState('complain', $order_info);

        //显示收货
        $order_info['if_receive'] = $model_order->getOrderOperateState('receive', $order_info);

        //显示物流跟踪
        $order_info['if_deliver'] = $model_order->getOrderOperateState('deliver', $order_info);

        //显示评价
        $order_info['if_evaluation'] = $model_order->getOrderOperateState('evaluation', $order_info);

        //显示分享
        // $order_info['if_share'] = $model_order->getOrderOperateState('share',$order_info);
        //显示系统自动取消订单日期
        if ($order_info['order_state'] == ORDER_STATE_NEW) {
            //$order_info['order_cancel_day'] = $order_info['add_time'] + ORDER_AUTO_CANCEL_DAY * 24 * 3600;

            $order_info['order_cancel_day'] = $order_info['add_time'] + ORDER_AUTO_CANCEL_DAY + 3 * 24 * 3600;
        }

        //显示快递信息
        if ($order_info['shipping_code'] != '') {
            $express = \Express::lists(true, 'id');
            $order_info['express_info']['e_code'] = $express[$order_info['extend_order_common']['shipping_express_id']]['e_code'];
            $order_info['express_info']['e_name'] = $express[$order_info['extend_order_common']['shipping_express_id']]['e_name'];
            $order_info['express_info']['e_url'] = $express[$order_info['extend_order_common']['shipping_express_id']]['e_url'];
        }

        //显示系统自动收获时间
        if ($order_info['order_state'] == ORDER_STATE_SEND) {
            $order_info['order_confirm_day'] = $order_info['delay_time'] + ORDER_AUTO_RECEIVE_DAY + 7 * 24 * 3600;
        }

        //如果订单已取消，取得取消原因、时间，操作人
        if ($order_info['order_state'] == ORDER_STATE_CANCEL) {
            $order_info['close_info'] = $model_order->getOrderLogInfo(array('order_id' => $order_info['order_id']), 'log_id desc');
        }

        foreach ($order_info['extend_order_goods'] as $value) {
            $value['image_60_url'] = img_url($value['goods_image'], 60);
            $value['image_240_url'] = img_url($value['goods_image'], 240);
            $value['goods_type_cn'] = orderGoodsType($value['goods_type']);
            $value['goods_url'] = url('index/goods/detail', array('goods_id' => $value['goods_id']));
            if ($value['goods_type'] == 5) {
                $order_info['zengpin_list'][] = $value;
            } else {
                $order_info['goods_list'][] = $value;
            }
        }

        if (empty($order_info['zengpin_list'])) {
            $order_info['goods_count'] = count($order_info['goods_list']);
        } else {
            $order_info['goods_count'] = count($order_info['goods_list']) + 1;
        }

        $this->assign('order_info', $order_info);

        //卖家发货信息
        if (!empty($order_info['extend_order_common']['daddress_id'])) {
            $daddress_info = model('Common/Daddress')->getAddressInfo(array('address_id' => $order_info['extend_order_common']['daddress_id']));
            $this->assign('daddress_info', $daddress_info);
        }

        return view();
    }
    
    /**
     * 物流跟踪
     */
    public function search_deliver(){
        $order_id	= input('order_id/d');
        if ($order_id <= 0) {
            return $this->error('参数错误');
        }

        $model_order	= model('Common/Order');
        $condition['order_id'] = $order_id;
        $condition['buyer_id'] = $this->member_id;
        $order_info = $model_order->getOrderInfo($condition,array('order_common','order_goods'));
        if (empty($order_info) || !in_array($order_info['order_state'],array(ORDER_STATE_SEND,ORDER_STATE_SUCCESS))) {
            return $this->error('未找到信息');
        }
        $this->assign('order_info',$order_info);

        //卖家信息
        $model_store	= model('Common/Store');
        $store_info		= $model_store->getStoreInfoByID($order_info['store_id']);
        $this->assign('store_info',$store_info);

        //卖家发货信息
        $daddress_info = model('Common/Daddress')->getAddressInfo(array('address_id'=>$order_info['extend_order_common']['daddress_id']));
        $this->assign('daddress_info',$daddress_info);

        //取得配送公司代码
        $express = \Express::lists(true, 'id');
        $this->assign('e_code',$express[$order_info['extend_order_common']['shipping_express_id']]['e_code']);
        $this->assign('e_name',$express[$order_info['extend_order_common']['shipping_express_id']]['e_name']);
        $this->assign('e_url',$express[$order_info['extend_order_common']['shipping_express_id']]['e_url']);
        $this->assign('shipping_code',$order_info['shipping_code']);

        $this->profile_menu('search','search');
        $this->assign('left_show','order_view');
        return $this->fetch();
    }

    /**
     * 从第三方取快递信息
     *
     */
    public function get_express()
    {
        return json(false);
        $url = 'http://www.kuaidi100.com/query?type=' . $_GET['e_code'] . '&postid=' . $_GET['shipping_code'] . '&id=1&valicode=&temp=' . random(4) . '&sessionid=&tmp=' . random(4);
        import('function.ftp');
        $content = dfsockopen($url);
        $content = json_decode($content, true);

        if ($content['status'] != 200)
            exit(json_encode(false));
        $content['data'] = array_reverse($content['data']);
        $output = array();
        if (is_array($content['data'])) {
            foreach ($content['data'] as $k => $v) {
                if ($v['time'] == '')
                    continue;
                $output[] = $v['time'] . '&nbsp;&nbsp;' . $v['context'];
            }
        }
        if (empty($output))
            exit(json_encode(false));
        if (strtoupper(CHARSET) == 'GBK') {
            $output = Language::getUTF8($output); //网站GBK使用编码时,转换为UTF-8,防止json输出汉字问题
        }

        echo json_encode($output);
    }

    /**
     * 买家订单状态操作
     *
     */
    public function change_state()
    {
        $state_type = input('state_type');
        $order_id = input('order_id/d');

        $model_order = model('Common/Order');

        $condition = [];
        $condition['order_id'] = $order_id;
        $condition['buyer_id'] = $this->member_id;
        $order_info = $model_order->getOrderInfo($condition);

        if ($state_type == 'order_cancel') {
            $result = $this->_order_cancel($order_info, input('post.'));
        } else if ($state_type == 'order_receive') {
            $result = $this->_order_receive($order_info, input('post.'));
        } else if (in_array($state_type, array('order_delete', 'order_drop', 'order_restore'))) {
            $result = $this->_order_recycle($order_info, input('get.'));
        } else {
            exit();
        }

        if (is_string($result)) {
            return $result;
        } else if (!$result['status']) {
            return showDialog($result['msg'], '', 'error');
        } else {
            return showDialog($result['msg'], 'reload', 'js');
        }
    }

    /**
     * 取消订单
     */
    private function _order_cancel($order_info, $post)
    {
        if (!$this->request->isPost()) {
            $this->assign('order_info', $order_info);
            return $this->fetch('order/cancel');
        } else {
            $model_order = model('Common/Order');
            $logic_order = model('Common/Order', 'logic');
            $if_allow = $model_order->getOrderOperateState('buyer_cancel', $order_info);
            if (!$if_allow) {
                return callback(false, '无权操作');
            }

            $msg = $post['state_info1'] != '' ? $post['state_info1'] : $post['state_info'];
            return $logic_order->changeOrderStateCancel($order_info, 'buyer', $this->member_info['name'], $msg);
        }
    }

    /**
     * 收货
     */
    private function _order_receive($order_info, $post)
    {
        if (!$this->request->isPost()) {
            $this->assign('order_info', $order_info);
            return $this->fetch('receive');
            exit();
        } else {
            $model_order = model('Common/Order');
            $logic_order = model('Common/Order', 'logic');
            $if_allow = $model_order->getOrderOperateState('receive', $order_info);
            if (!$if_allow) {
                return callback(false, '无权操作');
            }

            return $logic_order->changeOrderStateReceive($order_info, 'buyer', $this->member_info['name']);
        }
    }

    /**
     * 回收站
     */
    private function _order_recycle($order_info, $get)
    {
        $model_order = model('Common/Order');
        $logic_order = model('Common/Order', "logic");
        $state_type = str_replace(array('order_delete', 'order_drop', 'order_restore'), array('delete', 'drop', 'restore'), $get['state_type']);
        $if_allow = $model_order->getOrderOperateState($state_type, $order_info);
        if (!$if_allow) {
            return callback(false, '无权操作');
        }

        return $logic_order->changeOrderStateRecycle($order_info, 'buyer', $state_type);
    }

    /**
     * 订单支付页
     */
    public function pay()
    {
        $this->view->assign('step', 'step3');
        return view('cart/step3');
    }

    /**
     * 订单详情
     */
    public function show()
    {
        return view();
    }

    /**
     * 用户中心右边，小导航
     *
     * @param string	$menu_type	导航类型
     * @param string 	$menu_key	当前导航的menu_key
     * @return
     */
    private function profile_menu($menu_key = '')
    {
        $menu_array = array(
            array('menu_key' => 'member_order', 'menu_name' => '订单列表', 'menu_url' => url('member/order/index')),
            array('menu_key' => 'member_order_recycle', 'menu_name' => '回收站', 'menu_url' => url('member/order/index?recycle=1')),
        );
        $this->assign('member_menu', $menu_array);
        $this->assign('menu_key', $menu_key);
    }

}
